﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Web;
using WaveringLand_Launcher;
using WaveringLand_Launcher.Model;

namespace WaveringLand_Launcher.Tool
{
    class Program
    {
        static void Main(string[] args)
        {


            var oldfiles = JsonSerializer.Deserialize<List<WllFile>>(File.ReadAllText("index.json"));
            var wllfiles = new List<WllFile>();
            Console.WriteLine("开始分析.minecraft文件夹");
            var files = Directory.GetFiles(".minecraft").ToList();

            Console.WriteLine("开始分析.minecraft\\mods文件夹");
            files.AddRange(Directory.GetFiles(".minecraft\\mods"));

            foreach (var file in files)
            {
                var type = "";
                if (Path.GetDirectoryName(file).Contains("mods"))
                {

                    type = "Mods";
                }
                else if (Path.GetDirectoryName(file).Contains("shaderpacks"))
                {
                    type = "Shaderpacks";
                }
                else if (Path.GetDirectoryName(file).Contains("resourcepacks"))
                {
                    type = "Resourcepacks";
                }
                else if (Path.GetFileName(file) is "servers.dat")
                {
                    type = "ServersDat";
                }
                var path = file.Replace(Directory.GetCurrentDirectory(), "");
                var find = oldfiles.Find(x => x.Path == path);

                if(find != null)
                {
                    type = find.Category;
                }
                
                wllfiles.Add(new()
                {
                    Category = type,
                    MD5 = GetMd5(file),
                    Method = "Add",
                    Path = path,
                    Url = $"http://downloads.heerdev.top/{ HttpUtility.UrlEncode(file.Replace(Directory.GetCurrentDirectory(), "").Replace("\\", "/"))}"
                });
            }

            Console.WriteLine("分析完成，导出Json中");
            var opt = new JsonSerializerOptions();
            opt.Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping;
            ;
            File.WriteAllText("index.json", JsonSerializer.Serialize(wllfiles, opt));
            Console.WriteLine("到处Json完成，按任意键退出");
            Console.ReadKey();
            Environment.Exit(0);
        }

        static string GetMd5(string apath)
        {
            string md5 = "";
            using (var fs = new FileStream(apath, FileMode.Open))
            {
                md5 = BitConverter.ToString(new MD5CryptoServiceProvider().ComputeHash(fs)).Replace("-", "");
            }

            return md5;
        }
    }
}